//
//  RegisterViewController.m
//  E_Supermarket_ Merchants
//
//  Created by osoons on 15/6/1.
//  Copyright (c) 2015年 E_Supermarket_ Merchants. All rights reserved.
//

#import "MeranchRegisterViewController.h"

#import "BaseUrlConfig.h"
#import "Common.h"

#import "AFNetworking.h"
#import "LoadingView.h"
#import "NetWarningView.h"

@interface MeranchRegisterViewController ()

@end

@implementation MeranchRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
    [_v_Top.lalTitel setText:@"商家注册"];
    [_v_Top.btnGoback setHidden:NO];
    _v_Top.parentController = self.navigationController;
    
    [_v_Top.btnGoback removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_v_Top.btnGoback addTarget:self action:@selector(btnBack:) forControlEvents:UIControlEventTouchUpInside];

    //    D68E66
    _textPhoneNum.layer.borderColor = [UIColor orangeColor].CGColor;
    _textPhoneNum.layer.cornerRadius = 2.0;
    _textPhoneNum.layer.borderWidth = 2.0;
    
    _textPhoneNum.delegate  = self;
    _textSetPassword.delegate = self;
    _textSetAlginPassword.delegate = self;
    _textVerificationCode.delegate  = self;
    
    _textPhoneNum.returnKeyType = UIReturnKeyNext;
    _textSetPassword.returnKeyType = UIReturnKeyNext;
    _textSetAlginPassword.returnKeyType = UIReturnKeyNext;
    _textVerificationCode.returnKeyType = UIReturnKeyDefault;

    
    [_textPhoneNum becomeFirstResponder];
    
    
    
    [_btnVerification removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    [_btnVerification addTarget:self action:@selector(btnVerification:) forControlEvents:UIControlEventTouchUpInside];
    
    [_btnRegister removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_btnRegister addTarget:self action:@selector(btnRegister:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    // Do any additional setup after loading the view from its nib.
}
-(void)btnBack:(UIButton *)back
{
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    if (textField == _textPhoneNum) {
        [_textSetPassword becomeFirstResponder];
    }
    else if (textField == _textSetPassword) {
        [_textSetAlginPassword becomeFirstResponder];
    }
    else if (textField == _textSetAlginPassword) {
        [_textVerificationCode becomeFirstResponder];
    }
    
    [textField resignFirstResponder];
    return YES;
}


-(void)btnVerification:(UIButton *)Verification
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];


    [self VerifyCodeRequest];
    
}


-(void)btnRegister:(UIButton *)Register
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    BOOL VerifyMobile = [self VerifyMobileNumber:_textPhoneNum.text];
    if (!VerifyMobile) {
        UIAlertView *  alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"输入的手机号有误" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
        return ;
        
    }
    
    if (![_textSetPassword.text isEqualToString:_textSetAlginPassword.text ]) {
        
        UIAlertView *  alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"两次输入的密码不一致" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
        return ;
        
        
    }
    if (_textVerificationCode.text.length == 0) {
        
        UIAlertView *  alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入验证吗" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
        return ;
        
    }
    
    
    
    
    
    
    
    [self RegisterRequest];
    
    
}
//检测是否是手机号码
- (BOOL)VerifyMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     * 虚拟：170
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9]|70)\\d{8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    if ([regextestmobile evaluateWithObject:mobileNum] == YES)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

# pragma mark - network request 请求验证码

-(void)VerifyCodeRequest{
    [[LoadingView shareLoadingView] show];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setTimeoutInterval:10];
    //    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    
    
    
    NSString *   strUrl = [NSString stringWithFormat:@"%@", HostServer];
    NSDictionary *dicJSON   = @{
//                                @"method":Url_RegisterCode,
//                                @"phone":_textPhoneNum.text,
                            };
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicJSON options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSDictionary *param = nil;
    
    param   = @{
                    @"data":jsonString,
                };
    
    
     [manager GET:strUrl parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        

        NSDictionary * dicRespon  = responseObject;
        [self VerifyRequestWith:dicRespon];
        
        [[LoadingView shareLoadingView] dismissAnimated:YES];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
        [[LoadingView shareLoadingView] dismissAnimated:YES];
        [[NetWarningView sharedNetWarningView] show];  //警告网络异常
        NSLog(@"Error: %@", error);
        NSLog(@"请求出错了: - %@ %@",
              [error localizedDescription],
              [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
    }];
    
    
}

-(void)VerifyRequestWith:(NSDictionary *)dicRespon
{
    
    if ([[dicRespon objectForKey:@"success"] isEqualToString:@"true"]) {
        UIAlertView *  alter = [[UIAlertView alloc] initWithTitle:@"提示" message:[dicRespon objectForKey:@"message"] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
        
    }

}


# pragma mark - network request 注册接口

-(void)RegisterRequest{
    [[LoadingView shareLoadingView] show];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setTimeoutInterval:10];
    //    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    
    
    
    NSString *   strUrl = [NSString stringWithFormat:@"%@", HostServer];
    NSDictionary *dicJSON   = @{
//                                @"method":Url_Register,
//                                @"phone":_textPhoneNum.text,
//                                @"code":_textVerificationCode.text,
//                                @"username":_textPhoneNum.text,
//                                @"password":_textSetPassword.text
                                };
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicJSON options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSDictionary *param = nil;
    
    param   = @{
                    @"data":jsonString,
                    };
    
    
    [manager GET:strUrl parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSData * jsonData = responseObject;
        NSDictionary * dicRespon  = responseObject;
        [self RegisterRequestWith:dicRespon];
        
        [[LoadingView shareLoadingView] dismissAnimated:YES];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
        [[LoadingView shareLoadingView] dismissAnimated:YES];
        [[NetWarningView sharedNetWarningView] show];  //警告网络异常
        NSLog(@"Error: %@", error);
        NSLog(@"请求出错了: - %@ %@",
              [error localizedDescription],
              [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
    }];
    
    
}
-(void)RegisterRequestWith:(NSDictionary *)dicRespon
{
    
    if ([[dicRespon objectForKey:@"success"] isEqualToString:@"true"])
        {
            
        UIAlertView *  alter = [[UIAlertView alloc] initWithTitle:@"提示" message:[dicRespon objectForKey:@"message"] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
            [self.navigationController popViewControllerAnimated:YES];
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
